<script lang="ts" setup>
import lodash from 'lodash'
import moment from 'moment'
import { OrderApi } from '~/api/OrderApi'
import { Common } from '~/common'
import DateValueChart from '~/components/trends/DateValueChart.vue'
import { OrderModel } from '~/model'
import { NavBar } from 'vant';

interface DateValue {
  date: Date
  value: number
}
interface OrderGroupByDate {
  date: Date
  orders: OrderModel[]
}
const router = useRouter()
const LATEST_DAYS = 7
// const today = moment().format('YYYY-MM-DD')
const dateGt = moment(Date.now() - (LATEST_DAYS + 1) * 86400000).format('YYYY-MM-DD')
const dateLt = moment(Date.now() + 86400000).format('YYYY-MM-DD')

// x轴数据
const MS_OF_DAY = 86400 * 1000
const latestDays = computed(() => {
  const now = Date.now()
  const days = [] as Date[]
  for (let i = 0; i < LATEST_DAYS; i++) {
    const ts = now - (LATEST_DAYS - i - 1) * MS_OF_DAY
    days.push(new Date(moment(ts).format('YYYY-MM-DD')))
  }
  return days
})

function sameDay(d1: Date, d2: Date) {
  return moment(d1).format('YYYYMMDD') === moment(d2).format('YYYYMMDD')
}

const orders = ref([] as OrderModel[])
// const recentOrders: ComputedRef<OrderModel[]> = computed(() => {
//   const getFullDayTs = (d: Date) => {
//     d.setHours(0)
//     d.setMinutes(0)
//     d.setSeconds(0)
//     d.setMil
//     return d.valueOf()
//   }
//   const now = new Date()
//   return orders.value.filter((x) => {
//     return getFullDayTs(now) - getFullDayTs(x.date) <= LATEST_DAYS * MS_OF_DAY
//   })
// })

const recentOrdersGroupByDate = computed(() => {
  const groupByDate = lodash.groupBy(orders.value, x => moment(x.date).format('YYYY-MM-DD'))

  for (const day of latestDays.value) {
    const sDay = moment(day).format('YYYY-MM-DD')
    if (groupByDate[sDay] === undefined) {
      groupByDate[sDay] = []
    }
  }

  const res = [] as OrderGroupByDate[]
  for (const sDate of Object.keys(groupByDate)) {
    res.push({
      date: new Date(sDate),
      orders: groupByDate[sDate],
    })
  }

  return res
})

const salesGroupByDate: ComputedRef<DateValue[]> = computed(() => {
  // const sales = groupByDate[sDate].map(x => _totalAmount(x)).reduce((y, x) => y + x, 0)
  // data.value.push({
  //   date,
  //   sales,
  // })

  const _totalAmount = (_order: OrderModel) => {
    let s = _order.items.map(x => x.amount).reduce((y, x) => y + x, 0)
    if (_order.needDelivery) {
      s += _order.fare
    }
    return s
  }

  const ret = recentOrdersGroupByDate.value.map(x => ({
    date: x.date,
    value: x.orders.map(x => _totalAmount(x)).reduce((y, x) => y + x, 0),
  }))

  ret.sort((a, b) => a.date.valueOf() - b.date.valueOf())

  return ret
})

// 最近主要商品判断规则:
// - 最近销售商品按照销售额排序，取前6
const recectMainItemSaleQuantity = computed(() => {
  const orderItems = lodash.flatten(orders.value.map(x => x.items))
  const orderItemsGroup = lodash.groupBy(orderItems, x => x.material?.name)
  interface NameSalesQuantity {
    name: string
    quantity: number
    sales: number
  }
  const res: NameSalesQuantity[] = []
  for (const name of Object.keys(orderItemsGroup)) {
    res.push({
      name,
      quantity: orderItemsGroup[name].map(x => x.quantity).reduce((y, x) => y + x, 0),
      sales: orderItemsGroup[name].map(x => x.amount).reduce((y, x) => y + x, 0),
    })
  }

  return res.slice(0, 6)
})

function recentQuantityOf(name: string) {
  // console.log(latestDays.value)

  return latestDays.value.map((day) => {
    const sameDayOrder = orders.value.filter((order) => {
      return sameDay(order.date, day)
    })
    const orderItems = lodash.flatten(sameDayOrder.map(x => x.items))

    return {
      date: day,
      value: orderItems.filter(x => x.material?.name === name).map(x => x.quantity).reduce((y, x) => y + x, 0),
    }
  })
}

onMounted(() => {
  OrderApi.getPaged(1, 10000000, {
    date_start: dateGt,
    date_end: dateLt,
  })
    .then((paged) => {
      const res = paged.objects
      res.sort((a, b) => a.date.valueOf() - b.date.valueOf())
      orders.value = res
    })
  setTimeout(() => {
    console.log(salesGroupByDate.value)
  }, 5000)
})

function goDate(d: string) {
  console.log(d)
  router.push(`/trends/day?date=${d}`)
}
</script>

<template>
  <div>
    <NavBar
      title="统计数据"
      left-text="返回"
      left-arrow
      @click-left="$router.replace('/')"
    />
    <div p4>
      <div px1 py2 font-bold>
        销售额走势
      </div>
      <div mb2 paper flex-1 p0>
        <DateValueChart
          p2
          :data="salesGroupByDate"
          color="mediumseagreen"
          @date="goDate"
        />
      </div>
      <div px1 py2 font-bold>
        主要商品销售走势
      </div>
      <div flex flex-wrap>
        <div
          v-for="(item, index) in recectMainItemSaleQuantity"
          :key="index"

          class="trends-card"
          mb2 paper p0
        >
          <div px4 py2 font-bold b-b="1 solid gray-5">
            {{ item.name }}
          </div>
          <!--  -->
          <DateValueChart p2 :data="recentQuantityOf(item.name)" :color="Common.randomColor(item.name)" />
        </div>
      </div>
    </div>
    
  </div>
</template>

<route lang="yaml">
meta:
  title: 统计
</route>

<style scoped lang="scss">
.trends-card {
  width: calc(50vw - 1.25rem);
  &:nth-child(2n + 1) {
    margin-right: 0.5rem;
  }
}
</style>
